<template>
  <div>
      <el-breadcrumb>
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
        <el-row>
            <el-col>
                <el-button type="primary" @click="addDialogVisible=true">添加权限</el-button>
            </el-col>
        </el-row>
        <el-table :data="rolusList" border stripe>
            <el-table-column type="expand">
                <template v-slot="scope">
                    <el-row v-for="(item1,i1) in scope.row.children" :key="item1.id" :class="['bdbottom',i1 ===0 ?'bdtop':'','vcenter']" style="width:90%;margin: 0 auto;">
                        <el-col :span="5">
                            <el-tag closable  @close="removeRightById(scope.row,item3.id)">{{item1.authName}}</el-tag>
                            <i class="el-icon-caret-right"></i>
                        </el-col>
                        <el-col :span="19">
                            <el-row v-for="(item2,i2) in item1.children" :key="item2.id" :class="[i2 ===0 ?'':'bdtop','vcenter']">
                                <el-col :span="8">
                                    <el-tag type="success" closable @close="removeRightById(scope.row,item3.id)" >{{item2.authName}}</el-tag>
                                    <i class="el-icon-caret-right"></i>
                                </el-col>
                                <el-col :span="16" >
                                    <el-tag type="warning" v-for="(item3) in item2.children" :key="item3.id" closable @close="removeRightById(scope.row,item3.id)">{{item3.authName}}</el-tag>
                                </el-col>
                            </el-row>
                        </el-col>
                    </el-row>
                </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="角色名称" prop="roleDesc"></el-table-column>
            <el-table-column label="角色描述" prop="roleName"></el-table-column>
            <el-table-column label="操作" width="300px">
                 <template v-slot="scope">
                    <!-- 修改 -->
                    <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)">编辑</el-button>
                    <!-- 删除按钮 -->
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRolusById(scope.row.id)">删除</el-button>
                    <!-- 分配角色 -->
                    <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
                </template>
            </el-table-column>
        </el-table>
    </el-card>

        <!-- 添加权限的对话框 -->
    <el-dialog
    title="添加权限"
    :visible.sync="addDialogVisible"
    width="50%"
    @close="addDialogClosed"
    >
        <!-- 添加权限表单 -->
        <el-form ref="addFormRef" :model="addForm" label-width="90px" :rules="addFormRules">
            <el-form-item label="角色名称" prop="roleDesc">
                <el-input v-model="addForm.roleDesc"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleName">
                <el-input v-model="addForm.roleName"></el-input>
            </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addRolus">确 定</el-button>
        </span>
    </el-dialog>

    <!-- 修改权限对话框 -->
    <el-dialog
    title="修改权限"
    :visible.sync="editDialogVisible"
    width="50%"
    @close="editDialogClosed"
    >
        <el-form ref="editFormRef" :model="editForm" label-width="100px" :rules="addFormRules">
            <el-form-item label="角色名称" prop="roleDesc" >
                <el-input v-model="editForm.roleDesc" disabled></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleName">
                <el-input v-model="editForm.roleName"></el-input>
            </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editRolusInfo">确 定</el-button>
        </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
    title="提示"
    :visible.sync="rightsDialogVisible"
    width="30%"
    >
    <!-- 树形控件 -->
    <el-tree :data="rightslist" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref="treeRef" ></el-tree>

    <span slot="footer" class="dialog-footer">
        <el-button @click="rightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights" >确 定</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
    export default {
        data() {
            return {
                rolusList:[],
                addDialogVisible:false,
                editDialogVisible:false,
                addForm:{
                    roleDesc:'',
                    roleName:'',
                },
                editForm:{},
                addFormRules:{
                    roleDesc:[
                        { required: true, message: '请输入角色名称', trigger: 'blur' },
                    ],
                    roleName: [
                        { required: true, message: '请输入角色描述', trigger: 'blur' },
                    ],
                },
                rightsDialogVisible:false,
                rightslist:[],
                treeProps:{
                    label:'authName',
                    children:'children'
                },
                defKeys:[],
                roleId:''
            }
        },
        created(){
            this.getRolusList()
        },
        methods:{
            async getRolusList(){
                const {data:res} =  await this.$http.get('roles')
                if(res.meta.status !==200) return this.$message.error('获取权限列表失败')
                this.rolusList = res.data
            },
            addDialogClosed(){
                this.$refs.addFormRef.resetFields()
            },
            editDialogClosed(){
                this.$refs.editFormRef.resetFields()
            },
            addRolus(){
                this.$refs.addFormRef.validate(async valid=>{
                    if(!valid) return this.$message.error('输入有误')
                    const{data:res} = await this.$http.post('roles',this.addForm)
                    if(res.meta.status!==201){
                        return this.$message.error(res.meta.msg)
                    }
                    this.$message.success('角色添加成功')
                    this.addDialogVisible = false
                    this.getRolusList()
                })
            },
            // 修改用户信息按钮
            async showEditDialog(id){
                this.editDialogVisible = true
                const{data:res} = await this.$http.get('roles/'+id)
                this.editForm = res.data
            },
            // 修改权限信息并提交
            editRolusInfo(){
                this.$refs.editFormRef.validate(async valid=>{
                    if(!valid) return
                    const{data:res} = await this.$http.put('roles/'+this.editForm.roleId,
                    {id:this.editForm.roleId,
                    roleName:this.editForm.roleName,
                    roleDesc:this.editForm.roleDesc
                    })
                    if(res.meta.status!==200) return this.$message.error('修改失败'+res.meta.msg)
                    this.editDialogVisible = false
                    this.getRolusList()
                    this.$message.success('修改成功')
                })
            },
            // 点击删除按钮
            async removeRolusById(id){
                const confirmResult = await this.$confirm(
                '此操作将永久删除该权限, 是否继续?', 
                '提示', 
                {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).catch(err=>err)

                // 如果用户点击了确定返回字符串 confirm
                // 如果用户点击了取消返回字符串 cancel
                if(confirmResult !== 'confirm'){
                    return this.$message.info('已取消删除')
                }
                const {data:res} =  await this.$http.delete('roles/' + id)
                if(res.meta.status!==200) return this.$message.error('删除失败')
                this.$message.success('删除成功')
                this.getRolusList()
            },
            //根据Id删除对应的权限
            async removeRightById(role,rightId){
                const confirmResult = await this.$confirm(
                    '此操作将永久删除该用户, 是否继续?', 
                    '提示', 
                    {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                    }).catch(err=>err)

                    // 如果用户点击了确定返回字符串 confirm
                    // 如果用户点击了取消返回字符串 cancel
                    if(confirmResult !== 'confirm'){
                        return this.$message.info('已取消删除')
                    }
                    const {data:res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
                    if(res.meta.status!==200) return this.$message.error('删除失败')
                    role.children = res.data
                },
                // 点击分配权限按钮
                async showSetRightDialog(role){
                    this.roleId = role.id
                    // 获取所有权限的数据
                    const { data: res } = await this.$http.get('rights/tree')

                    if (res.meta.status !== 200) {
                        return this.$message.error('获取权限数据失败！')
                    }

                    // 把获取到的权限数据保存到 data 中
                    this.rightslist = res.data
                    this.defKeys = []
                     // 递归获取三级节点的Id
                    this.getLeafKeys(role, this.defKeys)
                    this.rightsDialogVisible=true

                },
                // 通过递归的形式，获取角色下所有三级权限的id，并保存到 defKeys 数组中
                getLeafKeys(node,arr){
                    if(!node.children){
                        return arr.push(node.id)
                    }

                    node.children.forEach(item => {
                        this.getLeafKeys(item,arr)
                    });
                },
                // 点击为角色分配权限
                async allotRights(){
                    const keys =[
                        ...this.$refs.treeRef.getCheckedKeys(),
                        ...this.$refs.treeRef.getHalfCheckedKeys(),
                    ]

                    const idStr = keys.join(',')
                    const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})

                    if (res.meta.status !== 200) {
                        return this.$message.error('分配权限失败！')
                    }
                    this.rightsDialogVisible = false
                    this.$message.success('分配权限成功！')
                    this.getRolesList()
                    
                }
        }
    }
</script>

<style scoped>
    .el-tag{
        margin: 7px;
    }
    .bdtop{
        border-top: 1px solid #eee;
    }
    .bdbottom{
        border-bottom: 1px solid #eee;
        
    }
    .vcenter{
        display: flex;
        align-items: center;
    }

</style>